<?php

//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                               |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: xiangminghu@clcw.com.cn                                        |
// +------------------------------------------------------------------------+
//


namespace AuctionCore\Finance;

use AuctionCore\CarDealer\Dealer;
use AuctionCore\CarResource\BreachCar;
use AuctionCore\CarResource\CarModel;
use AuctionCore\CarResource\SelfReceiveCar;
use AuctionCore\Other\Address;

/**
 * 应收退款
 * Class DealerRefund
 *
 * @author Xmh
 */
class ReceivableRefund
{

    private $ReceivableRefund;
    private $CarModel;
    private $Addr;

    public function __construct()
    {
        $this->ReceivableRefund = M('ReceivableRefund');
        $this->CarModel = new CarModel();
        $this->Addr = new Address();
    }

    /**
     * 获取应收退款的列表
     *
     * @param integer $page
     * @param int     $size
     * @param array   $params
     *
     * @return multitype:unknown string
     */
    public function get_receivable_refund_list($page = 1, $size = 10, $params)
    {
        $page = (int)$page < 1 ? 1 : (int)$page;
        $size = (int)$size < 1 ? 10 : (int)$size;
        $map = array();
        if ($params['status']) {
            $map['rr.status'] = ['eq', $params['status']];
        }
        if (!empty($params['location_area'])) {
            $map['c.location_area'] = ['eq', $params['location_area']];
        }
        if ($params['comefrom']) {
            $map['co.comefrom'] = ['eq', $params['comefrom']];
        }
        if (!empty($params['keywords'])) {
            $keywords = trim($params['keywords']);
            $where['o.order_no'] = ['LIKE', '%' . $keywords . '%'];
            $where['c.car_no'] = ['LIKE', '%' . $keywords . '%'];
            $where['co.seller_name'] = ['LIKE', '%' . $keywords . '%'];
            $where['co.phone'] = ['LIKE', '%' . $keywords . '%'];
            $where['_logic'] = 'OR';
            $map['_complex'] = $where;
        }
        if (empty($params['location_area']) && $params['bc_city']) {
            $map['c.location_area'] = ['in', $params['bc_city']];
        }
        //要查询的列表
        $cols = "o.order_id,o.order_no,o.status,o.car_id,
                 c.car_id,c.car_no,c.plate_suffix,c.plate_prefix,c.location_area,c.brand_id,c.series_id,c.model_id,
                 co.seller_name as contact_person,co.phone as contact_mobile,co.comefrom,co.comefrom_url,
                 rr.id,rr.receivable_time,rr.createtime";
        $prefix = C('DB_PREFIX');
        $order = 'rr.id DESC,o.order_id DESC';
        $total = M('receivable_refund')->alias('rr')
            ->join($prefix . "order as o ON o.order_id = rr.order_id")
            ->join($prefix . "cars as c ON c.car_id = rr.car_id")
            ->join($prefix . "car_owner as co ON co.owner_id = rr.owner_id")
            ->where($map)->count();
        $list = M('receivable_refund')->alias('rr')->field($cols)
            ->join($prefix . "order as o ON o.order_id = rr.order_id")
            ->join($prefix . "cars as c ON c.car_id = rr.car_id")
            ->join($prefix . "car_owner as co ON co.owner_id = rr.owner_id")
            ->where($map)->limit($size)->page($page)->order($order)->select();
//        echo M()->_sql();
        $show_from = \AuctionCore\Other\Channel::get_from();  //获取渠道来源信息
        if (!empty($list)) {
            foreach ($list as $key => $val) {
                $list[$key]['order_no'] = $val['order_no'];
                $list[$key]['location_area_name'] = $this->Addr->get_name_by_code($val['location_area']);
                $brand = $this->CarModel->get_model_by_id($val['brand_id'], 'brand');
                $series = $this->CarModel->get_model_by_id($val['series_id'], 'series');
                $model = $this->CarModel->get_model_by_id($val['model_id']);
                $list[$key]['car_no'] = $val['car_no'];
                $list[$key]['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
                $list[$key]['createtime'] = date("Y-m-d H:i", strtotime($val['createtime']));
                $list[$key]['receivable_time'] = date("Y-m-d H:i", strtotime($val['receivable_time']));
                //渠道来源
                if (!empty($val['comefrom'])) {
                    if (empty($val['comefrom_url'])) {
                        $channel_from = $show_from[$val['comefrom']];
                    } else {
                        $channel_from = "<a href='" . $val['comefrom_url'] . "' target='blank' rel='noreferrer'>" . $show_from[$val['comefrom']] . "</a>";
                    }
                } else {
                    $channel_from = '未知';
                }
                $list[$key]['channel_from'] = $channel_from;
            }
        }
        $result = array(
            'list' => $list,
            'total' => $total
        );
        return $result;
    }

    /**
     * 应收退款详情 -- 违约车辆退车
     *
     * @param  int $receivable_id
     *
     * @return mixed
     */
    public function receivable_refund_detail($receivable_id)
    {
        $condition['rr.id'] = ['eq', $receivable_id];
        //要查询的列表
        $cols = "o.order_id,o.order_no,o.status,o.car_id,o.last_time,
                 c.car_id,c.car_no,c.plate_suffix,c.plate_prefix,c.location_area,c.brand_id,c.series_id,c.model_id,
                 c.car_color,c.emission,c.pointer_mileage,c.reg_city,c.first_reg_date,c.composite_state,c.history_state,
                 c.accident_level,c.transfer_limit,c.vin,c.is_self_receive,
                 co.seller_name as contact_person,co.phone as contact_mobile,co.owner_type,co.contact_person as company_contact_person,
                 rr.id,rr.remark as receivable_remark,rr.receivable_time,rr.emp_id as receivable_emp,
                 rr.receivable_amount,rr.receivable_type,rr.status as receivable_status,rr.re_refund_type";
        $prefix = C('DB_PREFIX');
        $order = 'o.order_id DESC';
        $res = M('receivable_refund')->alias('rr')->field($cols)
            ->join($prefix . "order as o ON o.order_id = rr.order_id")
            ->join($prefix . "cars as c ON c.car_id = rr.car_id")
            ->join($prefix . "car_owner as co ON co.owner_id = rr.owner_id")
            ->where($condition)->order($order)->find();
//        echo M()->_sql();
        $brand = $this->CarModel->get_model_by_id($res['brand_id'], 'brand');
        $series = $this->CarModel->get_model_by_id($res['series_id'], 'series');
        $model = $this->CarModel->get_model_by_id($res['model_id']);
        $res['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
        $res['car_color'] = C('CAR_COLOR.' . $res['car_color']);
        $res['emission'] = C('INT_EMISSION_STD.' . $res['emission']);
        $res['plate_prefix'] = C('PLATE_PREFIX.' . $res['plate_prefix']);
        $res['pointer_mileage'] = round($res['pointer_mileage'] / 10000, 2);
        $res['location_area_name'] = $this->Addr->get_name_by_code($res['location_area']);
        $res['reg_city'] = $this->Addr->get_name_by_code($res['reg_city']);
        $res['car_plate_number'] = C('PLATE_PREFIX')[$res['plate_prefix']] . $res['plate_suffix'];
        //自收车辆 -- 退车信息
        if ($res['re_refund_type'] == 2) {
            $self_receive = new SelfReceiveCar();
            $self_receive_info = $self_receive->get_self_receive_refund($res['order_id']);
            //自收人信息
            if ($self_receive_info['self_receive_dealer_id']) {
                $dealer = Dealer::getDealerInfoById($self_receive_info['self_receive_dealer_id']);
                $d = new Dealer();
                $dealer = $d->get_contact_mobile_byAntNestfind($dealer);
                $res['emp_name'] = $dealer['contact_person'];
                $res['emp_phone'] = $dealer['contact_mobile'];
            }
            $res['compensate'] = $self_receive_info['compensate'];
            $res['deal_time'] = date("Y年m月d日 H:i", strtotime($self_receive_info['dealtime']));
            $res['remark'] = $self_receive_info['src_remark'];
        } else {   //违约车辆 --　退车信息
            $breach_car = new BreachCar($res['car_id']);
            $breach_car_info = $breach_car->get_breach_car_refund();
            if ($breach_car_info['bc_emp_id'] > 0) {
                $employee = \AuctionCore\Account\Back\Employee::user_info_id($breach_car_info['bc_emp_id']);
                $res['emp_name'] = $employee['real_name'];
                $res['emp_phone'] = $employee['mobile'];
            };
            $res['compensate'] = $breach_car_info['compensate'];
            $res['deal_time'] = date("Y年m月d日 H:i", strtotime($breach_car_info['deal_time']));
            $res['remark'] = $breach_car_info['bc_remark'];
        }
        //已付车款
        $pay = new \AuctionCore\Finance\Payment();
        $car_paid = $pay->get_car_paid($res['car_id']);
        $res['car_paid'] = $car_paid > 0 ? $car_paid : '0.00';

        if ($res['receivable_type'] == 1) {   //补偿
            $res['receivable_type_name'] = '补偿';
            $res['receivable_amount_total'] = sprintf("%1.2f", $res['car_paid'] - $res['compensate']);
        } elseif ($res['receivable_type'] == 2) { //扣除
            $res['receivable_type_name'] = '扣除';
            $res['receivable_amount_total'] = sprintf("%1.2f", $res['car_paid'] + $res['compensate']);
        }
        //应收退款信息
        if ($res['receivable_emp'] > 0) {
            $employee = \AuctionCore\Account\Back\Employee::user_info_id($res['receivable_emp']);
            $res['receivable_emp_name'] = $employee['real_name'];
        }
        $res['receivable_time'] = date("Y年m月d日 H:i", strtotime($res['receivable_time']));
        $res['owner_type_name'] = C('OWNER_TYPE_NAME')[$res['owner_type']];
        return $res;
    }


    /**
     * 应收退款详情 -- 自收车辆退车
     *
     * @param  int $receivable_id
     *
     * @return mixed
     */
    public function receivable_refund_self_detail($receivable_id)
    {
        $condition['rr.id'] = ['eq', $receivable_id];
        $condition['src.status'] = ['eq', 2];
        //要查询的列表
        $cols = "o.order_id,o.order_no,o.status,o.car_id,o.last_time,
                 c.car_id,c.car_no,c.plate_suffix,c.plate_prefix,c.location_area,c.brand_id,c.series_id,c.model_id,
                 c.car_color,c.emission,c.pointer_mileage,c.reg_city,c.first_reg_date,c.composite_state,c.history_state,
                 c.accident_level,c.transfer_limit,c.vin,
                 co.seller_name as contact_person,co.phone as contact_mobile,
                 rr.id,rr.remark as receivable_remark,rr.receivable_time,rr.emp_id as receivable_emp,
                 rr.receivable_amount,rr.receivable_type,rr.status as receivable_status,
                 src.src_id,src.emp_id as src_emp_id,src.compensate,src.remark as src_remark,src.deal_time";
        $prefix = C('DB_PREFIX');
        $order = 'o.order_id DESC';
        $res = M('receivable_refund')->alias('rr')->field($cols)
            ->join($prefix . "order as o ON o.order_id = rr.order_id")
            ->join($prefix . "cars as c ON c.car_id = rr.car_id")
            ->join($prefix . "car_owner as co ON co.owner_id = rr.owner_id")
            ->join($prefix . "self_receive_car as src ON src.car_id = rr.car_id")
            ->where($condition)->order($order)->find();
//        echo M()->_sql();
        $brand = $this->CarModel->get_model_by_id($res['brand_id'], 'brand');
        $series = $this->CarModel->get_model_by_id($res['series_id'], 'series');
        $model = $this->CarModel->get_model_by_id($res['model_id']);
        $res['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
        $res['car_color'] = C('CAR_COLOR.' . $res['car_color']);
        $res['emission'] = C('INT_EMISSION_STD.' . $res['emission']);
        $res['plate_prefix'] = C('PLATE_PREFIX.' . $res['plate_prefix']);
        $res['pointer_mileage'] = round($res['pointer_mileage'] / 10000, 2);
        $res['location_area_name'] = $this->Addr->get_name_by_code($res['location_area']);
        $res['reg_city'] = $this->Addr->get_name_by_code($res['reg_city']);
        $res['car_plate_number'] = C('PLATE_PREFIX')[$res['plate_prefix']] . $res['plate_suffix'];
        //退车信息
        if ($res['bc_emp_id'] > 0) {
            $employee = \AuctionCore\Account\Back\Employee::user_info_id($res['bc_emp_id']);
            $res['bc_emp_name'] = $employee['real_name'];
            $res['bc_emp_phone'] = $employee['mobile'];
        }
        $res['bc_deal_time'] = date("Y年m月d日 H:i", strtotime($res['deal_time']));
        //已付车款
        $pay = new \AuctionCore\Finance\Payment();
        $car_paid = $pay->get_car_paid($res['car_id']);
        $res['car_paid'] = $car_paid > 0 ? $car_paid : '0.00';

        if ($res['receivable_type'] == 1) {   //补偿
            $res['receivable_type_name'] = '补偿';
            $res['receivable_amount_total'] = sprintf("%1.2f", $res['car_paid'] - $res['compensate']);
        } elseif ($res['receivable_type'] == 2) { //扣除
            $res['receivable_type_name'] = '扣除';
            $res['receivable_amount_total'] = sprintf("%1.2f", $res['car_paid'] + $res['compensate']);
        }

        //应收退款信息
        if ($res['receivable_emp'] > 0) {
            $employee = \AuctionCore\Account\Back\Employee::user_info_id($res['receivable_emp']);
            $res['receivable_emp_name'] = $employee['real_name'];
        }
        $res['receivable_time'] = date("Y年m月d日 H:i", strtotime($res['receivable_time']));
        return $res;
    }


    /**
     * 创建应收退款
     *
     * @param array $data
     */
    public function add_receivable_refund($data = array())
    {
        if (empty($data)) {
            return false;
        }
        return $this->ReceivableRefund->add($data);
    }

    /**
     * 更新应收退款处理
     *
     * @param array $data
     */
    public function save_receivable_refund($data = array())
    {
        if (empty($data)) {
            return false;
        }
        $data['receivable_time'] = date("Y-m-d H:i:s", time());
        return $this->ReceivableRefund->save($data);
    }


    /**
     * 获取应收退款详情
     *
     * @param $id
     * @param $cols
     *
     * @return bool|mixed
     */
    public function get_receivable_refund($id, $cols = "*")
    {
        if ($id < 1) {
            return false;
        }
        return $this->ReceivableRefund->field($cols)->find($id);
    }
}
